﻿using System;
using System.Collections.Generic;
using System.Linq;

namespace UsefulExtensionMethods
{
    public static class StringExtensions
    {
        public static string Truncate(this string s, int maxLength)
        {
            if (String.IsNullOrEmpty(s))
                return String.Empty;
            else
            {
                if (s.Length > maxLength)
                    return s.Substring(0, maxLength);
                else
                    return s;
            }
        }

        public static string Truncate(this string s, int maxLength, string suffix)
        {
            if (String.IsNullOrEmpty(s))
                return String.Empty;
            else
            {
                if (s.Length > maxLength)
                    return s.Substring(0, maxLength) + suffix;
                else
                    return s;
            }
        }

        public static string ToSafeWebString(this string s)
        {
            return System.Text.RegularExpressions.Regex.Replace(s, @"[\W][\s]*", "-").ToLower();
        }

        public static string ToSafeWebString(this string s, string replacement)
        {
            return System.Text.RegularExpressions.Regex.Replace(s, @"[\W][\s]*", replacement).ToLower();
        }

        public static string RegexReplace(this string s, string pattern, string replacement)
        {
            return System.Text.RegularExpressions.Regex.Replace(s, pattern, replacement).ToLower();
        }

        public static string DefaultIfNullOrEmpty(this string s, string defaultValue)
        {
            if(String.IsNullOrEmpty(s))
                return defaultValue;
            else
                return s;
        }

        public static string ExceptionIfNullOrEmpty(this string obj, string message)
        {
            if (String.IsNullOrEmpty(obj))
                throw new Exception(message);
            else
                return obj;
        }

        public static string JoinNotNullOrEmpty(this string[] objs, string separator)
        {
            List<string> items = new List<string>();

            foreach (string s in objs)
            {
                if (!String.IsNullOrEmpty(s))
                    items.Add(s);
            }

            return String.Join(separator, items.ToArray());
        }
    }
}
